from django.db import models
from django.utils import timezone


class PermissionCategory(models.Model):
    """权限分组模型"""
    name = models.CharField(
        max_length=100, 
        verbose_name='分组名称'
    )
    description = models.TextField(
        blank=True, 
        null=True, 
        verbose_name='描述'
    )
    parent = models.ForeignKey(
        'self', 
        on_delete=models.CASCADE, 
        blank=True, 
        null=True, 
        verbose_name='父级分组',
        related_name='children'
    )
    sort_order = models.IntegerField(
        default=0, 
        verbose_name='排序'
    )
    created_at = models.DateTimeField(
        default=timezone.now, 
        verbose_name='创建时间'
    )

    class Meta:
        verbose_name = '权限分组'
        verbose_name_plural = '权限分组'
        db_table = 'permission_category'
        ordering = ['sort_order', 'name']

    def __str__(self):
        return self.name

    def get_full_name(self):
        """获取完整分组名称（包含父级）"""
        if self.parent:
            return f'{self.parent.get_full_name()} > {self.name}'
        return self.name


class SystemConfig(models.Model):
    """系统配置模型"""
    CONFIG_TYPES = [
        ('string', '字符串'),
        ('integer', '整数'),
        ('boolean', '布尔值'),
        ('json', 'JSON'),
    ]
    
    key = models.CharField(
        max_length=100, 
        unique=True, 
        verbose_name='配置键'
    )
    value = models.TextField(
        blank=True, 
        null=True, 
        verbose_name='配置值'
    )
    description = models.TextField(
        blank=True, 
        null=True, 
        verbose_name='描述'
    )
    config_type = models.CharField(
        max_length=20, 
        choices=CONFIG_TYPES, 
        default='string', 
        verbose_name='配置类型'
    )
    created_at = models.DateTimeField(
        default=timezone.now, 
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True, 
        verbose_name='更新时间'
    )

    class Meta:
        verbose_name = '系统配置'
        verbose_name_plural = '系统配置'
        db_table = 'system_config'

    def __str__(self):
        return f'{self.key}: {self.value}'

    def get_value(self):
        """根据类型返回配置值"""
        if self.config_type == 'boolean':
            return self.value.lower() in ['true', '1', 'yes']
        elif self.config_type == 'integer':
            try:
                return int(self.value)
            except (ValueError, TypeError):
                return 0
        elif self.config_type == 'json':
            import json
            try:
                return json.loads(self.value)
            except (ValueError, TypeError):
                return {}
        return self.value